package cn.sfturing.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class MailUtil {
	private String personal ="天津市医院预约系统";
	private static Logger log = LoggerFactory.getLogger(MailUtil.class);
	public boolean sendMail(String toAddress,String title ,String content){
		return sendMail(toAddress, personal, title, content);
		
	}
	@SuppressWarnings("static-access")
	//FIXME:添加异常，显示邮件发送情况。另外，邮件发送，改为异步发送；如果异步，发送成功与否的消息怎么处理？
	public  boolean sendMail(String toAddress, String personal ,String title ,String content){
		// 1.创建一个程序与邮件服务器会话对象 Session
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "SMTP");
		props.setProperty("mail.smtp.host", "smtp.qq.com");
		props.setProperty("mail.smtp.port", "465");
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		// 指定验证为true
		props.setProperty("mail.smtp.auth", "true");

// 验证账号及密码，密码需要是第三方授权码
		Session session = Session.getInstance(props,new Authenticator()
        {
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication
                ("2579288156@qq.com", "slojdiaijjjieajb");
            }
        });
		MimeMessage message = new MimeMessage(session);

		try {
			// 设置发送者
			message.setFrom(new InternetAddress("2579288156@qq.com"));
			// 设置发送方式与接收者
			message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress));
			// 设置主题
			message.setSubject("邮件发送测试");
			// 设置内容
			message.setContent(content, "text/html;charset=utf-8");
			// 主题
			message.setSubject(title);
			// 3.创建 Transport用于将邮件发送
			Transport.send(message);
		} catch (MessagingException e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return false ;
		}
		return true ;
	}
	
	public static void main(String[] args) {
		MailUtil mu=new MailUtil();
		mu.sendMail("2579288156@qq.com","PRO", "测试", "这是一封测试邮件");
		
	}

}
